const { wrongQuestionsAPI } = require('../../utils/api.js');

Page({
  data: {
    questionId: null,
    question: {},
    currentIndex: 1,
    total: 1,
    loading: false,
    error: ''
  },

  onLoad(options) {
    const { id } = options || {};
    this.setData({ questionId: id });
    if (!id) {
      this.setData({ error: '无效的题目ID' });
      wx.showToast({ title: '无效的题目ID', icon: 'none' });
      return;
    }
    this.fetchDetail(id);
  },

  navigateBack() {
    wx.navigateBack({ delta: 1 });
  },

  async fetchDetail(id) {
    this.setData({ loading: true, error: '' });
    try {
      const data = await wrongQuestionsAPI.getById(id);
      const optionsList = this.normalizeOptions(data?.options);
      const question = { ...data, optionsList };
      this.setData({ question: question || {}, loading: false });
    } catch (e) {
      console.error('加载错题详情失败', e);
      this.setData({ loading: false, error: e?.message || '加载失败' });
      wx.showToast({ title: '加载失败', icon: 'none' });
    }
  },

  // 将后端返回的 options 统一为 [{ key: 'A', value: '...' }, ...]
  normalizeOptions(options) {
    if (!options) return [];
    let obj = options;
    // 字符串则尝试解析为 JSON
    if (typeof obj === 'string') {
      try { obj = JSON.parse(obj); } catch (e) { return []; }
    }
    // 如果已经是数组，做必要的归一化
    if (Array.isArray(obj)) {
      return obj.map((item, idx) => {
        if (typeof item === 'string') {
          return { key: String.fromCharCode(65 + idx), value: this.toRich(item) };
        }
        if (item && typeof item === 'object') {
          const k = item.key ?? item.option ?? item.label ?? String.fromCharCode(65 + idx);
          const v = item.value ?? item.text ?? item.content ?? '';
          return { key: k, value: this.toRich(v) };
        }
        return { key: String.fromCharCode(65 + idx), value: this.toRich(String(item)) };
      });
    }
    // 普通对象 {A: '...', B: '...'}
    if (obj && typeof obj === 'object') {
      return Object.keys(obj).sort().map(k => ({ key: k, value: this.toRich(obj[k]) }));
    }
    return [];
  },

  // 纯文本转富文本，支持换行
  toRich(str) {
    if (!str) return '';
    const s = String(str);
    const looksLikeHtml = /<[^>]+>/.test(s);
    return looksLikeHtml ? s : s.replace(/\r?\n/g, '<br/>');
  }
});